package com.tcpengine.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

// 编码 | 解码 器
public class Encoder {
	// 网络协议解码
	public final static Msg decode(ByteBuf byteBuf) {	// 仅测试使用，这里没有考虑连包网络情况
		System.out.println("网络协议解码...");
		if (byteBuf.readableBytes() < Msg.MSG_HEADER_LEN) {
			return null;
		}
		byteBuf.markReaderIndex();
		int id = byteBuf.readInt();
		
		int bodyLen = byteBuf.readInt();
		if (byteBuf.readableBytes() < bodyLen) {	
			byteBuf.resetReaderIndex();
			return null;
		}
		if(1002 == id) {
			short temp = byteBuf.readShort();	// 1002 协议特殊的数据
			System.out.println("id=1002特殊的数据：" + temp);
		}
		ByteBuf body = Unpooled.buffer(bodyLen);
		byteBuf.readBytes(body);
		Msg msg = new Msg(id, bodyLen, body);
		return msg;
	}

	// 网络协议编码
	public final static ByteBuf encode(Msg msg) 
	{
		int len = msg.bodyLen + Msg.MSG_HEADER_LEN;
		ByteBuf buffer = Unpooled.buffer(len);
		buffer.writeInt(msg.id);
		buffer.writeInt(msg.bodyLen);
		buffer.writeBytes(msg.body);
		System.out.println("网络数据编码... msg.id=" + msg.id + "msg.bodyLen=" + msg.bodyLen + "msg.body=" + msg.body.toString());
		return buffer;
	}
}
